<template>
	<view class="form">
		<scroll-view class="scroll" scroll-y="true">
			<uv-form labelPosition="left" :model="form" :rules="rules" ref="form">
				<uv-form-item prop="title" borderBottom>
					<uv-input v-model="form.title" placeholder="好的标题会更有更多人看哦~~"></uv-input>
				</uv-form-item>
				<uv-form-item prop="title" borderBottom style="margin-top: 20rpx;">
					<textarea
						v-model="form.content"
						auto-height
						maxlength="1000"
						:show-confirm-bar="false"
						placeholder="请输入正文~~~"
						placeholder-style="color: #909399;"
					></textarea>
					<view class="total" style="text-align: right;" v-if="!articleId">{{ form.content.length }}/1000</view>
				</uv-form-item>
			</uv-form>
		</scroll-view>
		<view class="confirm bottom" v-if="!articleId">
			<button class="button" @click="handleSubmit">发布</button>
		</view>
	</view>
</template>

<script>
import { createArticle, getArticleDetail } from '@/apis/article/index.js';
export default {
	data() {
		return {
			articleId: null,
			form: {
				title: '',
				content: ''
			},
			rules: {
				title: { required: true, trigger: 'blur', message: '标题不能为空' },
				content: { required: true, trigger: 'blur', message: '内容不能为空' }
			}
		};
	},
	onLoad(option) {
		if (option.id != 0) {
			this.articleId = option.id;
			this.initData(option.id);
		}
	},
	onReady() {
		this.$refs['form'].setRules(this.rules);
	},
	methods: {
		async initData(id) {
			const res = await getArticleDetail(id);
			this.form = {
				title: res.data.title,
				content: res.data.content
			};
		},
		handleSubmit() {
			this.$refs['form']
				.validate()
				.then(async () => {
					const userId = this.$store.state.userInfo.id;
					const res = await createArticle({ ...this.form, userId });
					if (res.code === 200) {
						uni.showToast({ icon: 'success', title: '保存成功' });
					}
				})
				.catch(error => {
					return false;
				});
		}
	}
};
</script>

<style lang="scss">
page {
	background-color: #fff;
}
</style>

<style lang="scss" scoped>
.form {
	position: relative;
	padding: 20rpx;
	.scroll {
		height: calc(100vh - 150rpx);
	}
	textarea {
		width: 100%;
		min-height: 600rpx;
		margin-top: 20rpx;
		font-size: 32rpx;
	}
}
</style>
